"""
Fortran interface analysis for CodeMCP framework.

This module provides analysis of Fortran interface blocks and
generic procedures including operator overloading.
"""

import logging
from typing import Dict, List, Any, Set, Optional
from collections import defaultdict

from ...core.error_handler import AnalysisError, log_info


class InterfaceInfo:
    """Information about a Fortran interface."""
    
    def __init__(self, name: str, line_number: int = 0):
        self.name = name
        self.line_number = line_number
        self.procedures = []  # List of procedures in this interface
        self.is_generic = False
        self.is_operator = False
        self.is_assignment = False
        self.is_abstract = False
        self.operator_symbol = None  # For operator interfaces
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary representation."""
        return {
            'name': self.name,
            'line_number': self.line_number,
            'procedures': self.procedures,
            'is_generic': self.is_generic,
            'is_operator': self.is_operator,
            'is_assignment': self.is_assignment,
            'is_abstract': self.is_abstract,
            'operator_symbol': self.operator_symbol
        }


class InterfaceAnalyzer:
    """
    Fortran interface analyzer.
    
    Analyzes interface blocks, generic procedures, and operator overloading.
    """
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.interfaces = {}  # name -> InterfaceInfo
        self.generic_procedures = defaultdict(list)  # generic_name -> [procedure_names]
        self.operator_overloads = defaultdict(list)  # operator -> [procedure_names]
    
    def analyze_interfaces(self, parsed_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Analyze interfaces in parsed Fortran data.
        
        Args:
            parsed_data: Parsed Fortran file data
            
        Returns:
            Interface analysis results
        """
        try:
            filename = parsed_data.get('filename', 'unknown')
            log_info(f"Analyzing interfaces in {filename}")
            
            # Process interface blocks
            for interface_data in parsed_data.get('interfaces', []):
                self._process_interface(interface_data)
            
            result = {
                'filename': filename,
                'interfaces': {name: iface.to_dict() for name, iface in self.interfaces.items()},
                'generic_procedures': dict(self.generic_procedures),
                'operator_overloads': dict(self.operator_overloads),
                'statistics': self._compute_statistics()
            }
            
            log_info(f"Interface analysis complete for {filename}: "
                    f"{len(self.interfaces)} interfaces")
            
            return result
            
        except Exception as e:
            self.logger.error(f"Error analyzing interfaces: {e}")
            raise AnalysisError(f"Interface analysis failed: {e}")
    
    def _process_interface(self, interface_data: Dict[str, Any]):
        """Process a single interface block."""
        name = interface_data.get('name', 'unnamed')
        
        interface_info = InterfaceInfo(
            name=name,
            line_number=interface_data.get('line_number', 0)
        )
        
        interface_info.is_generic = interface_data.get('is_generic', False)
        interface_info.is_operator = interface_data.get('is_operator', False)
        interface_info.is_assignment = interface_data.get('is_assignment', False)
        interface_info.procedures = interface_data.get('procedures', [])
        
        if interface_info.is_operator:
            interface_info.operator_symbol = interface_data.get('operator_symbol')
            self.operator_overloads[interface_info.operator_symbol].extend(interface_info.procedures)
        
        if interface_info.is_generic:
            self.generic_procedures[name].extend(interface_info.procedures)
        
        self.interfaces[name] = interface_info
    
    def _compute_statistics(self) -> Dict[str, Any]:
        """Compute interface analysis statistics."""
        total_interfaces = len(self.interfaces)
        generic_count = len([i for i in self.interfaces.values() if i.is_generic])
        operator_count = len([i for i in self.interfaces.values() if i.is_operator])
        assignment_count = len([i for i in self.interfaces.values() if i.is_assignment])
        abstract_count = len([i for i in self.interfaces.values() if i.is_abstract])
        
        return {
            'total_interfaces': total_interfaces,
            'generic_interfaces': generic_count,
            'operator_interfaces': operator_count,
            'assignment_interfaces': assignment_count,
            'abstract_interfaces': abstract_count,
            'total_generic_procedures': len(self.generic_procedures),
            'total_operator_overloads': len(self.operator_overloads)
        }